package com.hnld.transform.handler.impl;

import cn.afterturn.easypoi.csv.CsvImportUtil;
import cn.afterturn.easypoi.csv.entity.CsvImportParams;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hnld.transform.cosntant.TransformConstant;
import com.hnld.transform.entity.IRIRoute;
import com.hnld.transform.entity.Parameter;
import com.hnld.transform.entity.RIRoute;
import com.hnld.transform.handler.IOtherFileHandler;
import com.hnld.transform.util.CSVFileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

public class OtherIRIFileHandler implements IOtherFileHandler {
    private static List<String> targets = Lists.newArrayList();
    private static Map<String, String> sourceMap = Maps.newHashMap();
    private static String routePath = "/路面图像/";

    static {
        //
        targets.add("DR");
        targets.add("IRI");
        targets.add("LBI");
        targets.add("RIFile");
        //对应的源文件夹目录
        sourceMap.put("DR", "/路面景象/识别结果/");
        sourceMap.put("IRI", "/平整度数据/IRI/");
        sourceMap.put("LBI", "/LBI/");
        sourceMap.put("RIFile", "/平整度数据/RIFile/");
    }

    @Override
    public String getType() {
        return "IRI";
    }

    /**
     * 处理非图像类IRI数据
     *
     * @param files         路径下的所有文件
     * @param targetDir     /非图像类数据/路线编码+/IRI
     * @param area          区县名称
     * @param areaRouteCode 路线编码
     */
    @Override
    public void handleFileType(List<File> files, String targetDir, String area, String areaRouteCode, Parameter parameter, Map<String, Integer> twoDirectionsMap) {
        System.out.println("处理区县【" + area + "】的路线【" + areaRouteCode + "】非图像类IRI数据");
        //先把路线方向的最后的字母编号去掉
        String routeCode = areaRouteCode.substring(0, areaRouteCode.length() - 1);
        //IRI文件在区县的路面平整度文件夹下
        String IRIPath = parameter.getBaseSourcePath() + area + "/" + sourceMap.get(getType());
        //获取IRIPath下的所有文件，并过滤出符合上面routeCode的文件
        //List<File> sourceIRIFiles = FileUtil.loopFiles(IRIPath);
        //优先
        List<File> fileList = files.stream().filter(sourceIRIFile -> sourceIRIFile.getName().startsWith(routeCode)).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(fileList)) {
            System.out.println("未找到区县【" + area + "】的路线【" + areaRouteCode + "】非图像类IRI数据");
            TransformConstant.IRI_ROUTE.add(areaRouteCode);
            return;
        }
        boolean exist = false;
        //读取里面的文件，然后
        for (File sourceIRIFile : fileList) {
            String name = sourceIRIFile.getName();
            List<IRIRoute> iriRoutes = CSVFileUtils.readCSVData(IRIPath + "/" + name, IRIRoute.class, true);
            if (CollectionUtil.isEmpty(iriRoutes)) {
                continue;
            }
            String direction = iriRoutes.get(0).getDirection();
            String directionCode = TransformConstant.ROUTE_DIRECTION.get(direction);
            //重复标识
            Integer duplicateIdentification = 1;
            if (!twoDirectionsMap.isEmpty()) {
                duplicateIdentification = Optional.ofNullable(twoDirectionsMap.get(routeCode)).orElse(0);
            }
            if (duplicateIdentification > 1) {//重复通路线编码不同方向
                if (areaRouteCode.equals(routeCode + directionCode)) {
                    exist = true;
                    //如果路线编号和方向编号相同，则说明是目标文件
                    //文件名 C00A431102-IRI-K0+000-20230729081204.csv 转换成 C00A431102A-IRI-0.000-20230729081204.txt
                    String[] nameSplit = name.split("-");
                    //K0+000
                    String stakeSegment = nameSplit[2];
                    //转换成0.000
                    stakeSegment = stakeSegment.replace("K", "").replace("+", ".");
                    //文件名后缀.csv去掉
                    String nameSuffix = nameSplit[3].split("\\.")[0];
                    String newFileName = areaRouteCode + "-" + getType() + "-" + stakeSegment + "-" + nameSuffix + ".txt";
                    writeCSVData(iriRoutes, targetDir + "/" + newFileName);
                }
            } else {
                exist = true;
                //如果路线编号和方向编号相同，则说明是目标文件
                //文件名 C00A431102-IRI-K0+000-20230729081204.csv 转换成 C00A431102A-IRI-0.000-20230729081204.txt
                String[] nameSplit = name.split("-");
                //K0+000
                String stakeSegment = nameSplit[2];
                //转换成0.000
                stakeSegment = stakeSegment.replace("K", "").replace("+", ".");
                //文件名后缀.csv去掉
                String nameSuffix = nameSplit[3].split("\\.")[0];
                String newFileName = areaRouteCode + "-" + getType() + "-" + stakeSegment + "-" + nameSuffix + ".txt";
                writeCSVData(iriRoutes, targetDir + "/" + newFileName);
            }
        }
        if (!exist) {
            System.out.println("未找到区县【" + area + "】的符合路线【" + areaRouteCode + "】方向的非图像类IRI数据");
            TransformConstant.IRI_ROUTE.add(areaRouteCode);
        }


    }

    private static void writeCSVData(List<IRIRoute> iriRoutes, String targetPath) {
        List<String> writeContent = new ArrayList<>();
        List<String> titleList = CSVFileUtils.getTitleList(IRIRoute.class, TransformConstant.excludeTitle, "IRI_左(m/km)", 1);
        titleList.add(2, "IRI_右(m/km)");
        String titleContent = String.join(",", titleList);
        writeContent.add(titleContent);
        iriRoutes.forEach(data -> {
            if (StringUtils.isBlank(data.getStake())) {
                return;
            }
            //拼接内容
            //起点桩号(km),IRI_左(m/km),IRI_右(m/km),IRI(m/km),速度(m/s)
            String content = data.getStake() + "," + data.getIRILeft() + "," + data.getIRIRight() + "," + data.getIRI() + "," + data.getSpeed();
            writeContent.add(content);
        });
        //写入文件
        FileUtil.writeLines(writeContent, targetPath, Charset.defaultCharset(), true);
    }

    public static void main(String[] args) {
        String filePath = "E:\\报部数据转格式\\零陵区\\平整度数据\\RIFile\\20230729\\C003431102\\C003431102-LP-K0+636-20230729082154.csv";
        CsvImportParams csvParams = new CsvImportParams(CsvImportParams.UTF8);
        List objects = CsvImportUtil.importCsv(FileUtil.getInputStream(filePath), RIRoute.class, csvParams);
        System.out.println(objects.size());
    }

}
